package com.security;

import com.pojo.entity.SysPermission;
import com.pojo.vo.UserVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 执行动态访问配置
 */
@Component
public class AccessControlCheck {
    public boolean checkPermission(HttpServletRequest request, Authentication authentication) {
        //从安全性上下文取得用户信息
        UserVo userVo = (UserVo) authentication.getPrincipal();
        List<SysPermission> permissionList = userVo.getPermissionList();
        //过滤页面请求
        permissionList = permissionList.stream().filter(p -> {
            return p.getPermission() != null && p.getPermission().startsWith("btn:");
        }).collect(Collectors.toList());
        //判断权限
        for (int i = 0; i < permissionList.size(); i++) {
            SysPermission permission = permissionList.get(i);
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(permission.getUrl(), permission.getMethod());
            if (matcher.matches(request)) return true;
        }
        return false;
    }
}
